﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System.Configuration;

namespace SOLInfo.GEN.Repository.Config
{
    public class AutoConfiguracao
    {
        private static ISessionFactory _session;
        public static ISessionFactory session
        {
            get
            {
                if (_session == null)
                    _session = CreateSessionFactory();
                return _session;
            }
        }

        private static ISessionFactory CreateSessionFactory()
        {
            // Configura o mapeamento fluente
            return Fluently.Configure()
                .Database(
                    MsSqlConfiguration.MsSql2008.ConnectionString(c => c
                        .Is(@"Password=eousudv;Persist Security Info=True;User ID=sa;Initial Catalog=GENDB;Data Source=CESAR-NOTE\CSV")))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<AutoConfiguracao>())
                .ExposeConfiguration(cfg =>
                {
                    if (ConfigurationManager.AppSettings["GenerateSchema"] == "1")
                    {
                        try
                        {
                            new SchemaValidator(cfg).Validate();
                        }
                        catch
                        {
                            new SchemaExport(cfg).Create(false, true);
                        }
                    }
                })
                .BuildSessionFactory();
        }
    }
}
